"""
KidsBuddy 1.0 用户关系映射
定义用户之间的关系和权限管理
"""

from datetime import datetime
from typing import Dict, List, Optional, Set, Any
from dataclasses import dataclass, field
from enum import Enum

from .user import BaseUser, Child, Parent, UserRole


class RelationshipType(Enum):
    """关系类型枚举"""
    PARENT = "parent"               # 父母
    GUARDIAN = "guardian"           # 监护人
    GRANDPARENT = "grandparent"     # 祖父母/外祖父母
    TEACHER = "teacher"             # 教师
    TUTOR = "tutor"                # 家教
    CAREGIVER = "caregiver"        # 看护人
    SIBLING = "sibling"            # 兄弟姐妹
    FRIEND = "friend"              # 朋友


class PermissionLevel(Enum):
    """权限级别枚举"""
    FULL = "full"                  # 完全权限：可以查看和修改所有数据
    MONITOR = "monitor"            # 监控权限：可以查看学习数据和进度
    LIMITED = "limited"            # 有限权限：只能查看基本信息
    EMERGENCY = "emergency"        # 紧急权限：只在紧急情况下可访问


class Permission(Enum):
    """具体权限枚举"""
    # 用户管理权限
    VIEW_PROFILE = "view_profile"
    EDIT_PROFILE = "edit_profile"
    DELETE_USER = "delete_user"

    # 学习数据权限
    VIEW_LEARNING_DATA = "view_learning_data"
    EDIT_LEARNING_SETTINGS = "edit_learning_settings"
    VIEW_PROGRESS_REPORTS = "view_progress_reports"

    # 会话管理权限
    START_SESSION = "start_session"
    END_SESSION = "end_session"
    VIEW_SESSION_HISTORY = "view_session_history"

    # 内容管理权限
    MANAGE_CONTENT = "manage_content"
    APPROVE_CONTENT = "approve_content"

    # 系统设置权限
    MANAGE_PARENTAL_CONTROLS = "manage_parental_controls"
    VIEW_SYSTEM_LOGS = "view_system_logs"
    EMERGENCY_ACCESS = "emergency_access"


@dataclass
class UserRelationship:
    """用户关系模型"""
    id: str
    from_user_id: str              # 关系发起者ID
    to_user_id: str                # 关系接受者ID
    relationship_type: RelationshipType
    permission_level: PermissionLevel
    permissions: Set[Permission] = field(default_factory=set)
    is_active: bool = True
    is_verified: bool = False      # 关系是否已验证
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    verified_at: Optional[datetime] = None
    verified_by: Optional[str] = None  # 验证者ID
    notes: str = ""

    def verify_relationship(self, verified_by: str):
        """验证关系"""
        self.is_verified = True
        self.verified_at = datetime.now()
        self.verified_by = verified_by
        self.updated_at = datetime.now()

    def add_permission(self, permission: Permission):
        """添加权限"""
        self.permissions.add(permission)
        self.updated_at = datetime.now()

    def remove_permission(self, permission: Permission):
        """移除权限"""
        self.permissions.discard(permission)
        self.updated_at = datetime.now()

    def has_permission(self, permission: Permission) -> bool:
        """检查是否有特定权限"""
        return permission in self.permissions

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "id": self.id,
            "from_user_id": self.from_user_id,
            "to_user_id": self.to_user_id,
            "relationship_type": self.relationship_type.value,
            "permission_level": self.permission_level.value,
            "permissions": [p.value for p in self.permissions],
            "is_active": self.is_active,
            "is_verified": self.is_verified,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
            "verified_at": self.verified_at.isoformat() if self.verified_at else None,
            "verified_by": self.verified_by,
            "notes": self.notes
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'UserRelationship':
        """从字典创建实例"""
        permissions = {Permission(p) for p in data.get("permissions", [])}

        # 处理日期字段
        created_at = datetime.fromisoformat(data["created_at"]) if data.get(
            "created_at") else datetime.now()
        updated_at = datetime.fromisoformat(data["updated_at"]) if data.get(
            "updated_at") else datetime.now()
        verified_at = None
        if data.get("verified_at"):
            try:
                verified_at = datetime.fromisoformat(data["verified_at"])
            except ValueError:
                verified_at = None

        return cls(
            id=data["id"],
            from_user_id=data["from_user_id"],
            to_user_id=data["to_user_id"],
            relationship_type=RelationshipType(data["relationship_type"]),
            permission_level=PermissionLevel(data["permission_level"]),
            permissions=permissions,
            is_active=data.get("is_active", True),
            is_verified=data.get("is_verified", False),
            created_at=created_at,
            updated_at=updated_at,
            verified_at=verified_at,
            verified_by=data.get("verified_by"),
            notes=data.get("notes", "")
        )


class RelationshipManager:
    """关系管理器"""

    def __init__(self):
        self.relationships: Dict[str, UserRelationship] = {}
        self._permission_templates = self._init_permission_templates()

    def _init_permission_templates(self) -> Dict[PermissionLevel, Set[Permission]]:
        """初始化权限模板"""
        return {
            PermissionLevel.FULL: {
                Permission.VIEW_PROFILE,
                Permission.EDIT_PROFILE,
                Permission.VIEW_LEARNING_DATA,
                Permission.EDIT_LEARNING_SETTINGS,
                Permission.VIEW_PROGRESS_REPORTS,
                Permission.START_SESSION,
                Permission.END_SESSION,
                Permission.VIEW_SESSION_HISTORY,
                Permission.MANAGE_PARENTAL_CONTROLS,
                Permission.EMERGENCY_ACCESS
            },
            PermissionLevel.MONITOR: {
                Permission.VIEW_PROFILE,
                Permission.VIEW_LEARNING_DATA,
                Permission.VIEW_PROGRESS_REPORTS,
                Permission.VIEW_SESSION_HISTORY
            },
            PermissionLevel.LIMITED: {
                Permission.VIEW_PROFILE,
                Permission.VIEW_PROGRESS_REPORTS
            },
            PermissionLevel.EMERGENCY: {
                Permission.VIEW_PROFILE,
                Permission.EMERGENCY_ACCESS
            }
        }

    def create_relationship(
        self,
        from_user_id: str,
        to_user_id: str,
        relationship_type: RelationshipType,
        permission_level: PermissionLevel = PermissionLevel.MONITOR
    ) -> UserRelationship:
        """创建用户关系"""
        import uuid

        relationship_id = f"rel_{uuid.uuid4().hex[:8]}"

        # 根据权限级别设置默认权限
        default_permissions = self._permission_templates.get(
            permission_level, set())

        relationship = UserRelationship(
            id=relationship_id,
            from_user_id=from_user_id,
            to_user_id=to_user_id,
            relationship_type=relationship_type,
            permission_level=permission_level,
            permissions=default_permissions.copy()
        )

        self.relationships[relationship_id] = relationship
        return relationship

    def get_relationship(self, relationship_id: str) -> Optional[UserRelationship]:
        """获取关系"""
        return self.relationships.get(relationship_id)

    def get_user_relationships(self, user_id: str, as_from: bool = True) -> List[UserRelationship]:
        """获取用户的所有关系"""
        relationships = []
        for rel in self.relationships.values():
            if as_from and rel.from_user_id == user_id:
                relationships.append(rel)
            elif not as_from and rel.to_user_id == user_id:
                relationships.append(rel)
        return relationships

    def check_permission(self, from_user_id: str, to_user_id: str, permission: Permission) -> bool:
        """检查用户是否有对另一个用户的特定权限"""
        for rel in self.relationships.values():
            if (rel.from_user_id == from_user_id and
                rel.to_user_id == to_user_id and
                rel.is_active and
                rel.is_verified and
                    rel.has_permission(permission)):
                return True
        return False

    def get_children_for_parent(self, parent_id: str) -> List[str]:
        """获取家长的所有子女ID"""
        children_ids = []
        for rel in self.relationships.values():
            if (rel.from_user_id == parent_id and
                rel.relationship_type in [RelationshipType.PARENT, RelationshipType.GUARDIAN] and
                    rel.is_active and rel.is_verified):
                children_ids.append(rel.to_user_id)
        return children_ids

    def get_parents_for_child(self, child_id: str) -> List[str]:
        """获取儿童的所有家长ID"""
        parent_ids = []
        for rel in self.relationships.values():
            if (rel.to_user_id == child_id and
                rel.relationship_type in [RelationshipType.PARENT, RelationshipType.GUARDIAN] and
                    rel.is_active and rel.is_verified):
                parent_ids.append(rel.from_user_id)
        return parent_ids

    def remove_relationship(self, relationship_id: str) -> bool:
        """删除关系"""
        if relationship_id in self.relationships:
            del self.relationships[relationship_id]
            return True
        return False

    def deactivate_relationship(self, relationship_id: str) -> bool:
        """停用关系"""
        if relationship_id in self.relationships:
            self.relationships[relationship_id].is_active = False
            self.relationships[relationship_id].updated_at = datetime.now()
            return True
        return False
